package com.example.esc_im_client.utils;

import android.os.AsyncTask;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;

/**
 * @ClassName: HttpUtils
 * @Description:
 * @Author: 墨渍
 * @Date: 2023/10/19 22:59
 **/
public class HttpUtils {

    private static final OkHttpClient client = new OkHttpClient();

    public interface HttpCallback {
        void onSuccess(String response);

        void onError(String errorMessage);
    }

    // 发起 GET 请求
    public static void doGet(String url, HttpCallback callback) {
        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    callback.onSuccess(responseData);
                } else {
                    callback.onError("Request failed");
                }
            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                callback.onError(e.getMessage());
            }
        });
    }

    // 发起 POST 请求
    public static void doPost(String url, String json, HttpCallback callback) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(json, JSON);

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    callback.onSuccess(responseData);
                } else {
                    callback.onError("Request failed");
                }
            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                callback.onError(e.getMessage());
            }
        });
    }

}
